const loginModel = require('../../model/login/loginModel')
const userModel = require('../../model/users/userModel')
const Token = require('../../module/token')
class loginService {
    //获取用户登录
    async postLogin(req, res) {
        let account = req.body.account
        console.log(account)
        let password = req.body.password
        const { results: data } = await loginModel.longin(account, password)
        if (data.length != 0) {
            //加密
            let id = {account,password}
            let tokenKey = Token.en(id)
            let tokenDe = Token.de(tokenKey)
            tokenDe = JSON.stringify(tokenDe)
            data[0]["token"] = tokenKey
            data[0]["tokenDe"] = tokenDe
            res.json({
                data,
                meta: {
                    msg: '登录成功',
                    status: 200
                }
            })
        } else {
            return res.json({
                meta: {
                    msg: '登录失败',
                    status: 404
                }
            })
        }
    }
    //创建用户
    async postSignUp(req,res){
      let account = req.body.account
      let password = req.body.password
      console.log(account)
      const {results:data} = await userModel.queryAddUser(account)
      if(data.length == 0){
        const results = await loginModel.signUp(account,password)
        return res.json({
            meta:{
                msg:'添加新用户成功',
                status:200
            }
        })
      }else{
        return res.json({
            meta: {
              msg: '添加新用户失败',
              status: 404
            }
          })
      }
    }
    //解密
    async postDe(req,res){
        let token = req.body.token
        let {tokenKey} = Token.de(token)
        console.log(token)
        console.log(tokenKey)
        let account = tokenKey.account
        const{results:data} = await userModel.queryAddUser(account)
        console.log(data)
        res.json({
            data,
            meta:{
                msg:'解密成功',
                status:200
            }
        })
    }
}

module.exports = new loginService()